import { useFetch } from "nuxt/app"

interface CzCloudOptions {
    method?: 'POST' | 'GET' | 'DELETE' | 'PUT',
    body?: Record<string, string>,
    headers?: Record<string, string>,
    query?: Record<string, string>,
    params?: Record<string, string>
}

interface CzCloudResponse {
    code: 500 | 200,
    data: any,
    msg: string
}

export default async function (name: `/${string}/${string}/${string}`, options?: CzCloudOptions): Promise<CzCloudResponse> {
    if (!options) {
        options = {}
    }

    const { data, error } = await useFetch<CzCloudResponse>(`${process.env.NUXT_CHENGZHI_GETWAY}/api${name}`, {
        method: options.method || 'GET',
        body: options.body,
        headers: options.headers,
        query: options.query,
        params: options.params,
        parseResponse: JSON.parse,
        credentials: 'include',
    })

    if (error != null) {
        return Promise.resolve({
            code: 500,
            data: null,
            msg: error.value?.message || '请求失败'
        })
    }
    return Promise.resolve(data.value as CzCloudResponse)
}